package com.basic.technology.study.introduction.thread.queue;

import java.util.PriorityQueue;
import java.util.concurrent.ArrayBlockingQueue;

public class BlockQueue {
    private int queueSize = 10;

    private ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(queueSize);

    public static void main(String[] args) {
        BlockQueue blockQueue = new BlockQueue();
        producer producer = blockQueue.new producer();
        consumer consumer = blockQueue.new consumer();
        producer.start();
        consumer.start();

    }


    class producer extends Thread {
        @Override
        public void run() {
            produce();
        }

        public void produce() {
            while (true) {
                try {
                    queue.put(1);
                    System.out.println("向队列中插入一个元素，队列剩余空间: " + (queueSize - queue.size()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    class consumer extends Thread{
        @Override
        public void run() {
         consume();
        }

        public void consume(){
            while (true){
                try {
                    queue.take();
                    System.out.println("从队列中取走一个元素，队列剩余 "+ queue.size()+ "个元素");
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

}
